package com.xian.im.common.utils.sys;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xian.im.common.exception.GlobalErrorCode;
import com.xian.im.common.result.RestResult;
import com.xian.im.common.result.RestResultBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

/**
 * 响应工具类
 */
@Slf4j
public class ResponseUtil {

    private ResponseUtil() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * z
     * 通过流写到前端
     *
     * @param objectMapper 对象序列化
     * @param response
     * @param msg          返回信息
     * @param httpStatus   返回状态码
     * @throws IOException
     */
    public static void responseWriter(ObjectMapper objectMapper, HttpServletResponse response, String msg, int httpStatus) throws IOException {

        RestResult<Object> result = RestResultBuilder.builder().success( ).code(httpStatus).message(msg).build();
        responseWrite(objectMapper, response, result);
    }

    /**
     * 通过流写到前端
     *
     * @param objectMapper 对象序列化
     * @param response
     * @param obj
     */
    public static void responseSucceed(ObjectMapper objectMapper, HttpServletResponse response, Object obj) throws IOException {
        RestResult<Object> result = RestResultBuilder.builder().success( ).data(obj).build();
        responseWrite(objectMapper, response, result);
    }

    /**
     * 通过流写到前端
     *
     * @param objectMapper
     * @param response
     * @param msg
     * @throws IOException
     */
    public static void responseFailed(ObjectMapper objectMapper, HttpServletResponse response, String msg) throws IOException {
        RestResult<Object> result = RestResultBuilder.builder().failure( ).message(msg).build();
        responseWrite(objectMapper, response, result);
    }

    private static void responseWrite(ObjectMapper objectMapper, HttpServletResponse response, RestResult<Object> result) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        try (
                Writer writer = response.getWriter()
        ) {
            writer.write(objectMapper.writeValueAsString(result));
            writer.flush();
        }
    }

    /**
     * 发送文本。使用UTF-8编码。
     *
     * @param response HttpServletResponse
     * @param text     发送的字符串
     */
    public static void renderText(HttpServletResponse response, String text) {
        render(response, "text/plain;charset=UTF-8", text);
    }

    /**
     * 发送json。使用UTF-8编码。
     *
     * @param response HttpServletResponse
     * @param text     发送的字符串
     */
    public static void renderJson(HttpServletResponse response, Object text) {
        render(response, "application/json;charset=UTF-8", JSONObject.toJSONString(text));
    }

    /**
     * 发送xml。使用UTF-8编码。
     *
     * @param response HttpServletResponse
     * @param text     发送的字符串
     */
    public static void renderXml(HttpServletResponse response, String text) {
        render(response, "text/xml;charset=UTF-8", text);
    }

    public static void renderJson(HttpServletResponse response, GlobalErrorCode errorCode) throws IOException {
        response.setHeader("Content-Type", "application/json;charset = utf-8");
        response.setStatus(errorCode.getCode());
        response.getWriter().write(JSON.toJSONString(RestResultBuilder.builder().failure().code(errorCode.getCode()).message(errorCode.getMessage()).build()));
    }

    public static void renderJson(HttpServletResponse response, GlobalErrorCode errorCode, Integer status) throws IOException {
        response.setHeader("Content-Type", "application/json;charset = utf-8");
        response.setStatus(status);
        response.getWriter().write(JSON.toJSONString(RestResultBuilder.builder().failure().code(status).message(errorCode.getMessage()).build()));
    }

    public static void renderJson(HttpServletResponse response, String msg, Integer status) throws IOException {
        response.setHeader("Content-Type", "application/json;charset = utf-8");
        response.setStatus(status);
        response.getWriter().write(JSON.toJSONString(RestResultBuilder.builder().failure().code(status).message(msg).build()));
    }

    /**
     * 发送内容。使用UTF-8编码。
     *
     * @param response
     * @param contentType
     * @param text
     */
    public static void render(HttpServletResponse response, String contentType, String text) {
        response.setContentType(contentType);
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        PrintWriter pWriter = null;
        try {
            pWriter = response.getWriter();
            pWriter.write(text);
            pWriter.flush();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(pWriter);
        }
    }
}
